<?php

namespace app\api\controller;

use app\api\exception\ApiException;
use app\api\model\User;
use app\common\lib\short\Short;

class Build extends ApiController
{
	/**
	 * 单个生成
	 */
	public function single()
	{
		$data = (new \app\api\validate\BuildValidate())->go($this->request->post());
		$appid = $data['appid'];
		$url = $data['url'];
		$scene = $data['scene'];
		$user = User::getUserByAppid($appid);
        User::chkIp($this->request->ip(),$user);
        if ($user->status !== \app\common\model\User::NORMAL) {
            throw new ApiException('用户已被禁用', 40003);
        }
        try {
			$short = Short::instance($this->app->redisManage->getRedis())->generate($url, $scene, $user);
			return $this->response->success($short);
		} catch (\Exception $exception) {
			throw new ApiException($exception->getMessage(), $exception->getCode());
		}
	}

	/**
	 * 批量生成
	 * @return \think\Response
	 * @throws ApiException
	 */
	public function batch()
	{
		$data = $this->request->post();
		if (!isset($data['urlmap'], $data['appid'])) {
			throw new ApiException('缺少参数');
		}
		//TODO:去除重复URL
		$urlMap = $data['urlmap'];

		if (count($urlMap) > 300) {
			throw new ApiException('一次不得超过300条链接');
		}
		foreach ($urlMap as &$value) {
			$value['appid'] = $data['appid'];
		}
		$appid = $data['appid'];
		(new \app\api\validate\BuildValidate())->batch(true)->go($urlMap);
		$user = User::getUserByAppid($appid);
        User::chkIp($this->request->ip(),$user);
        if ($user->status !== \app\common\model\User::NORMAL) {
            throw new ApiException('用户已被禁用', 40003);
        }
		try {
			$data = Short::instance($this->app->redisManage->getRedis())->batch($urlMap, $user);
			$message = $data['message'];
			unset($data['message']);
			return $this->response->success($data, $message);
		} catch (\Exception $exception) {
			throw new ApiException($exception->getMessage(), $exception->getCode());
		}
	}
}
